import React, { useEffect, useState } from 'react'
import {Table,Tag,Button,Modal,Popover ,Switch } from 'antd'
import {EditOutlined,DeleteOutlined,ExclamationCircleOutlined} from '@ant-design/icons'
import axios from 'axios'
const { confirm } = Modal;

export default function RightList() {
  const[dataSource,setDataSource]=useState([])
  useEffect(()=>{
   
    axios.get("http://localhost:8000/rights?_embed=children").then(res=>{
        const list=res.data
        console.log(list);
        // list[0].children=""
        list.forEach(item=>{
          if(item.children.length===0){
            item.children=""
          }
        })
       setDataSource(list)
    })
  },[])

  
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      render:(id)=> {
        return <b>{id}</b>
      },
    },
    {
      title: '权限名称',
      dataIndex: 'title',
    },
    {
      title: '权限路径',
      dataIndex: 'key',
      render:(key)=>{
        return  <Tag color="orange">{key}</Tag>
      }
    },
    {
      title: '操作',
      render:(item)=>{
        return <div>
           <Button danger shape="circle" onClick={()=>showDeleteConfirm(item)}  icon={<DeleteOutlined />}/>
           <Popover content={<div style={{textAlign:"center"}}>
            <Switch checked={item.pagepermisson} onChange={()=>switchMethod(item)}></Switch> </div>} title="配置权限是否可用" trigger={item.pagepermisson===undefined? '' : 'click'}>
            <Button type="primary" shape="circle" icon={<EditOutlined />}  disabled={item.pagepermisson===undefined} />
            </Popover>
        
        </div>
      }
    },
  ];
  const switchMethod=(item)=>{
    item.pagepermisson=item.pagepermisson===1?0:1;
    setDataSource([...dataSource])
    // console.log(item);
    if(item.grade===1){
      axios.patch(`http://localhost:8000/rights/${item.id}`,{pagepermisson:item.pagepermisson})
    }else{
      axios.patch(`http://localhost:8000/children/${item.id}`,{pagepermisson:item.pagepermisson})
    }
  }
  const showDeleteConfirm = (item) => {
    confirm({
      title: '你确认要删除吗?',
      icon: <ExclamationCircleOutlined />,
      // content: 'Some descriptions',
      okType: 'danger',
      okText: '确认',
      cancelText: '取消',
      onOk() {
       deleteMethod(item)
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  };
  const deleteMethod=(item)=>{
    // console.log(item);
   if(item.grade===1){
    setDataSource(dataSource.filter(data=>data.id!==item.id))
    axios.delete(`http://localhost:8000/rights/${item.id}`)
   }else if(item.grade===2){
   let list=dataSource.filter(data=>data.id===item.rightId)
   list[0].children=list[0].children.filter(data=>data.id!==item.id)
  //  console.log(list);
   setDataSource(list)
   axios.delete(`http://localhost:8000/children/${item.id}`)
   }
  }
  return (
    <div>
      <Table dataSource={dataSource} columns={columns} pagination={{
        pageSize:5
      }}/>
    </div>
  )
}
